package cz.muni.fi.pa165.dundd.daoimpl;

import cz.muni.fi.pa165.dundd.entity.Administrator;
import cz.muni.fi.pa165.dundd.dao.AdministratorDAO;
import cz.muni.fi.pa165.dundd.entity.Hero;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Repository;

/**
 *
 * @author xdemocko
 */
@Repository
public class AdministratorDAOImpl implements AdministratorDAO {

    @PersistenceContext
    private EntityManager em;

    @Override
    public void createAdministrator(Administrator admin) {
        em.persist(admin);
    }

    @Override
    public void updateAdministrator(Administrator admin) {
        em.merge(admin);
    }

    @Override
    public void deleteAdministrator(Administrator admin) {
        em.remove(em.contains(admin) ? admin : em.merge(admin));
    }

    @Override
    public List<Administrator> retrieveAllAdministrators() {
        TypedQuery<Administrator> cq = em.createQuery("SELECT a FROM Administrator a", Administrator.class);
        return cq.getResultList();
    }

    @Override
    public Administrator retrieveAdministratorById(Long id) {
        return em.find(Administrator.class, id);
    }

    @Override
    public Administrator retrieveAdministrator(String name) {
        if (name == null || name.equals("")) {
            throw new IllegalArgumentException("name must not be empty/null");
        }
        Administrator admin = (Administrator) em.createQuery("SELECT a FROM Administrator a WHERE a.name = :name").setParameter("name", name).getSingleResult();
        return admin;
    }
}
